package cn.edu.neu.controller.user;

import cn.edu.neu.model.TravelNotes;
import cn.edu.neu.model.User;
import cn.edu.neu.service.TravelNotesService;
import cn.edu.neu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.List;

@Controller
@RequestMapping("/travelNotes")
public class TravelNotesController {
    @Autowired
    private TravelNotesService travelNotesService;
    @Autowired
    private UserService userService;
    @RequestMapping("/getTravelNotesList")
    private String getTravelNotesList(Model model){
        List<TravelNotes> travelNotesList=travelNotesService.getTravelNotesList();
        model.addAttribute("travelNotesList",travelNotesList);
        return "/user/TravelNotes";
    }
    @RequestMapping("toAddPage")
    public String toAddPage(){
        return "/user/publish";
    }
    @RequestMapping("/addTravelNotes")
    public String addTravelNotes(TravelNotes travelNotes, MultipartFile fileUpload, HttpSession session) {
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            // 如果当前用户为空或者用户状态为 0，则重定向到登录页面
            return "redirect:/user/login";
        }

        try {
            File directory = new File("src/main/resources");
            String reportPath = directory.getCanonicalPath();
            String path = "/static/img/travel/";
            String dirPath = reportPath + path;

            File filePath = new File(dirPath);
            if (!filePath.exists()) {
                filePath.mkdirs();
            }
            String originalFilename = fileUpload.getOriginalFilename();
            fileUpload.transferTo(new File(dirPath + originalFilename));
            travelNotes.setImg("/img/travel/" + originalFilename);

        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }

        travelNotes.setUser_id(currentUser.getUser_id());
        travelNotesService.insertTravelNotes(travelNotes);
        return "redirect:/travelNotes/getTravelNotesList";
    }

    @RequestMapping("/toDetailPage/{id}/{userId}")
    public String toDetailPage(@PathVariable("id") Integer id,
                               @PathVariable("userId")Integer user_id,Model model){
        TravelNotes travelNotes=travelNotesService.getTravelNotesById(id);
        User user=userService.getUserById(user_id);
        model.addAttribute("travelNotes",travelNotes) ;
        model.addAttribute("user",user) ;
        return "/user/travel/details";
    }

}
